let config = {
    oid: 18,
    brand_code: 'miand',
    host: 'https://www.zjsuichong.com/min/wx',
    host1: 'https://www.zjsuichong.com/min/wxapp',
    tx_host: 'https://www.zjsuichong.com/app',
    qrcodeurl: 'https://www.zjsuichong.com', //二维码链接地址
    headerkey: '',
}


function appHttpRequest(url, params, successCallback, canCallback = function () {
}) {
    wx.showLoading({
        title: 'loading...',
        mask: true
    });
    wx.request({
        url: config.tx_host + url,
        method: 'POST',
        header: {
            'content-type': 'application/json',
            'openid': getApp().globalData.openID,
            'brand-code': config.brand_code,
            'client': 'wx'
        },
        data: params,
        dataType: 'json',
        success: function (res) {
            wx.hideLoading();
            // console.log(res);
            if (!res.data) {
                canCallback()
                wx.showToast({
                    title: "系统繁忙",
                    icon: 'none',
                    duration: 2000
                });
            }
            switch (res.data.code) {
                case 301:
                    canCallback()
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000
                    });
                    break;
                case 500:
                    canCallback()
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000
                    });
                    break;
                default:
                    successCallback(res.data)
                    break;
            }
        },
        fail: function (res) {
            wx.hideLoading();
            canCallback();
            wx.showToast({
                title: "系统繁忙",
                icon: 'none',
                duration: 2000
            });
        }
    });
}


// 请求后台接口（封装wx.request）
function httpRequest(url, params, successCallback, canCallback = function () {
}) {
    wx.showLoading({
        title: 'loading...',
        mask: true
    });
    wx.request({
        url: config.host + url,
        method: 'POST',
        header: {
            'content-type': 'application/json',
            'openid': getApp().globalData.openID,
            'brand-code': config.brand_code,
            'client': 'wx'
        },
        data: params,
        dataType: 'json',
        success: function (res) {
            wx.hideLoading();
            // console.log(res);
            if (!res.data) {
                canCallback()
                wx.showToast({
                    title: "系统繁忙",
                    icon: 'none',
                    duration: 2000
                });
            }
            switch (res.data.code) {
                case 0:
                    canCallback()
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000
                    });
                    break;
                case 401:
                    canCallback()
                    wx.showToast({
                        title: "未登录/未授权",
                        icon: 'none',
                        duration: 2000
                    });
                    break;
                case 403:
                    canCallback()
                    wx.showToast({
                        title: "非法请求",
                        icon: 'none',
                        duration: 2000
                    });
                    break;
                default:
                    successCallback(res.data)
                    break;
            }
        },
        fail: function (res) {
            wx.hideLoading();
            canCallback();
            wx.showToast({
                title: "系统繁忙",
                icon: 'none',
                duration: 2000
            });
        }
    });
}

// 请求后台接口（封装wx.request）
function httpSystem(url, params, successCallback, canCallback = function () {
}) {
    wx.showLoading({
        title: 'loading...',
        mask: true
    });
    wx.request({
        url: config.host1 + url,
        method: 'POST',
        header: {
            'content-type': 'application/json',
            'openid': getApp().globalData.openID,
            'brand-code': config.brand_code,
            'client': 'wx'
        },
        data: params,
        dataType: 'json',
        success: function (res) {
            wx.hideLoading();
            console.log(res);
            if (!res.data) {
                canCallback()
                wx.showToast({
                    title: "系统繁忙",
                    icon: 'none',
                    duration: 2000
                });
            }
            switch (res.data.code) {
                case 0:
                    canCallback()
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000
                    });
                    break;
                case 401:
                    canCallback()
                    wx.showToast({
                        title: "未登录/未授权",
                        icon: 'none',
                        duration: 2000
                    });
                    break;
                case 403:
                    canCallback()
                    wx.showToast({
                        title: "非法请求",
                        icon: 'none',
                        duration: 2000
                    });
                    break;
                default:
                    successCallback(res.data)
                    break;
            }
        },
        fail: function (res) {
            wx.hideLoading();
            canCallback();
            wx.showToast({
                title: "系统繁忙",
                icon: 'none',
                duration: 2000
            });
        }
    });
}

// 微信支付 发起支付
function wxPayPayment(amount, type, sn, extra, successCallback, completeCallback) {
    httpRequest('/wxPayRecharge', {
        amount: amount,
        type: type,
        sn: sn,
        extra: extra
    }, function (result) {
        if (result.code == 1) {
            let payments = result.data.params;
            let order_id = result.data.order_id;
            wx.requestPayment({
                timeStamp: payments.timeStamp,
                nonceStr: payments.nonceStr,
                package: payments.package,
                signType: 'MD5',
                paySign: payments.paySign,
                success(res) {
                },
                fail(res) {
                    wx.hideLoading();
                    wx.showToast({
                        title: "支付未完成",
                        icon: 'none',
                        duration: 2000
                    });
                },
                complete(res) {
                    if (res.errMsg == "requestPayment:ok") {
                        successCallback(order_id);
                    } else {
                        wx.hideLoading();
                        wx.showToast({
                            title: "您取消了支付",
                            icon: 'none',
                            duration: 2000
                        });
                        successCallback(0);
                    }
                }
            })
        } else {
            completeCallback();
            wx.hideLoading();
            wx.showToast({
                title: "支付失败",
                icon: 'none',
                duration: 2000
            });
        }
    })
}

// 微信创建微信分订单
function wxPayFreeze(amount, sn, successCallback, completeCallback) {
    httpRequest('/doWxfree', {
        sn: sn,
        amount: amount
    }, function (res) {
        if (res.code == 1) {
            let payments = res.data.params;
            // 将支付分小程序appid存储起来
            wx.navigateToMiniProgram({
                appId: payments.miniprogram_appid,
                path: payments.miniprogram_path,
                extraData: {
                    mch_id: payments.mch_id,
                    package: payments.package,
                    timestamp: payments.timestamp,
                    nonce_str: payments.nonce_str,
                    sign_type: payments.sign_type,
                    sign: payments.sign
                },
                envVersion: 'release', // 正式版
                success() {
                    // 跳转微信分小程序成功
                    // console.log("====>跳转微信分小程序成功");
                    getApp().globalData.miniprogram_appid = payments.miniprogram_appid;
                    getApp().globalData.create_wxfree = 1; // 微信分租借
                    getApp().globalData.conduct_sn = res.data.sn;
                    successCallback(res.data.auth_id);
                },
                fail() {
                    wx.showToast({
                        title: "创建微信分失败",
                        icon: 'none',
                        duration: 2000
                    });
                },
                complete() {
                }
            });
        } else {
            completeCallback();
            wx.showToast({
                title: "创建微信分失败",
                icon: 'none',
                duration: 2000
            });
        }
    })
}

//分页处理
function navpages(data,page,pagenum){
    console.log(data);
    if(data==null ||data.length==0){
        // console.log(1);
        return {'isflus':false};
    }
    let i = ((page-1)*pagenum);
    let newdata = [];
    for (let index = i,k = 0; index <= data.length && k<=pagenum ; index++,k++) {
        if(index == data.length){
            // console.log(2);
            return {'data':newdata,'isflus':false}
        }
        if( k==pagenum){
            // console.log(3);
            return {'data':newdata,'isflus':true}
        }
        newdata[k] =  data[index];
    }
}

//上传图片
function send_photo(data, successfun) {
    var that = this
    for (let i = 0; i < data.length; i++) {
      wx.uploadFile({
        url: "https://www.zjsuichong.com/sys/common/upload", //仅为示例，非真实的接口地址 自己写映射你Java接口的路径
        filePath: data[i] + "",
        name: 'file',
        success: function(res) {
            let data  = res.data;
            data = JSON.parse(data);
            if(data.code==0){
                successfun(data.url)
            }else{
                wx.showToast({
                  title: '图片上传失败！',
                  icon:'none',
                })
            }                                           
          
        },
        fail:function(res){
            wx.showToast({
                title: '图片上传失败！',
                icon:'none',
              })
        }
      })
    }
  }

module.exports = {
    config: config,
    httpRequest: httpRequest,
    AppHttpRequest: appHttpRequest,
    wxPayPayment: wxPayPayment,
    wxPayFreeze: wxPayFreeze,
    httpSystem:httpSystem,
    navpages:navpages,
    send_photo:send_photo
}